package com.xmmxjy.system.listener;

import com.xmmxjy.system.entity.UserEntity;
import com.xmmxjy.system.shiro.ShiroSessionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashSet;
import java.util.Set;

/**
 * 在线用户查看，登录以后存入到ServletContext
 */
public class LoginListener implements HttpSessionListener,ServletContextListener {

    private static Logger logger = LoggerFactory.getLogger(LoginListener.class);

    private ServletContext application = null;

    public void contextDestroyed(ServletContextEvent sce) {
        logger.info("context destory");
    }

    public void contextInitialized(ServletContextEvent sce) {
        logger.info("context init");
        application = sce.getServletContext();
        Set<UserEntity> onlineUserSet = new HashSet<UserEntity>();
        application.setAttribute("onlineUserSet", onlineUserSet);
    }

    public void sessionCreated(HttpSessionEvent se) {
        logger.info("session create");
    }

    public void sessionDestroyed(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        Set<UserEntity> onlineUserSet = (Set<UserEntity>)application.getAttribute("onlineUserSet");
        UserEntity userEntity = (UserEntity)session.getAttribute(ShiroSessionUtils.LOGIN_ATTRIVUTE_NAME);
        onlineUserSet.remove(userEntity);
        application.setAttribute("onlineUserSet", onlineUserSet);
        onlineUserSet = (Set<UserEntity>)application.getAttribute("onlineUserSet");
        logger.info(onlineUserSet.toString());
        logger.info(userEntity + "超时退出");
        logger.info("session destory !");
    }

}